import axios from 'axios';

/**
 * token刷新方法，
 * 1、当第一次出现401的时候，立即从api里请求token，并将“异步体”保存为 refreshPromise
 * 2、后续的请求相当于都是给 apiRefreshToken 添加then
 * 3、当token刷新完毕，refreshPromise 应当清空为下次做准备
 */
class RefreshToken {
  constructor() {
    this.refreshPromise = undefined;
  }
  apiRefreshToken() {
    if (!this.refreshPromise) {
      this.refreshPromise = new Promise(resolve => {
        // 获取到token，存放到本地缓存，此处忽略
        let data = new FormData();
        data.append('username', '17863007235');
        data.append('password', '666666');
        data.append('grant_type', 'password');
        axios
          .post(
            // 'http://124.71.198.113:8301/auth/oauth/token?grant_type=password&username=17863007235&password=666666',
            '/test/oauth/token',
            data,
            {
              headers: {
                Authorization: 'Basic ZmViczoxMjM0NTY='
              }
            }
          )
          .then(res => {
            console.log(res);
            sessionStorage.setItem('token', res.data.access_token);
          });
        setTimeout(() => {
          this.refreshPromise = undefined;
          resolve();
        }, 3000);
      });
    }
    return this.refreshPromise;
  }
  refreshIsLoading() {
    return Boolean(this.refreshPromise);
  }
}
export default new RefreshToken();
